import React, { useState, useEffect, useRef } from 'react';
import { Popup, Toast } from 'antd-mobile';
import styles from './Guang.module.css';
import {useNavigate} from 'react-router-dom'
import adVideoUrl from '../Lyf/img/1.mp4'

export default function Guang() {
  const [visible, setVisible] = useState(false);
  const [countdown, setCountdown] = useState(30);
  const videoRef = useRef(null);
  const timerRef = useRef(null);
  const navigate=useNavigate()

  // 使用可靠的视频源（确保支持跨域）
//   const adVideoUrl = "http://vjs.zencdn.net/v/oceans.mp4";
// const adVideoUrl = "https://media.w3.org/2010/05/sintel/trailer.mp4"
  // 组件加载后自动播放广告
  useEffect(() => {
    const timer = setTimeout(() => {
      playAd();
    }, 1000); // 延迟1秒后自动播放（模拟页面加载完成）

    return () => {
      clearTimeout(timer);
      clearInterval(timerRef.current);
    };
  }, []);

  // 开始播放广告
  const playAd = () => {
    setVisible(true);
    setCountdown(30);
    
    // 开始倒计时
    timerRef.current = setInterval(() => {
      setCountdown(prev => {
        if (prev <= 1) {
          clearInterval(timerRef.current);
          return 0;
        }
        return prev - 1;
      });
    }, 1000);
    
    // 播放视频
    if (videoRef.current) {
      videoRef.current.play().catch(e => {
        console.error("视频播放失败:", e);
        Toast.show("广告加载失败，请重试");
      });
    }
  };

  // 关闭广告
    const closeAd = () => {
      if (countdown > 0) {
          Toast.show(`请观看完广告（剩余${countdown}秒）`);
          return;
      }
      
      clearInterval(timerRef.current);
      setVisible(false);
      
      // 计算一天后的到期时间
      const now = new Date();
      const expireDate = new Date(now.getTime() + 24 * 60 * 60 * 1000); // 当前时间加24小时
      
      // 保存会员信息到本地存储
      const memberData = {
          memberType: "广告会员",
          vipLevel: 1,
          expireDate: expireDate.toISOString(),
          amount: 0,
          source: "ad" // 标记来源为广告
      };
      localStorage.setItem('currentMember', JSON.stringify(memberData));
      
      Toast.show("广告观看完成，已获得1天会员");
      navigate('/vippage');
  };

  return (
    <div className={styles.container}>
      {/* 移除了手动触发按钮 */}
      
      
        <div className={styles.adContainer}>
          <video
            ref={videoRef}
            className={styles.adVideo}
            src={adVideoUrl}
            muted
            autoPlay
            playsInline
            loop={false}
            onEnded={closeAd} // 视频播放结束后自动关闭
          />
          
          <div 
            className={styles.closeButton}
            onClick={closeAd}
          >
            {countdown > 0 ? `${countdown}s` : '关闭'}
          </div>
          
          <div className={styles.adBadge}>广告</div>
        </div>
      
    </div>
  );
}